package org.lionsoul.websnail.sample;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.lionsoul.websnail.Spider;
import org.lionsoul.websnail.downloader.webdriver.SnailWebDriver;
import org.lionsoul.websnail.downloader.webdriver.WebDriverDownloader;
import org.lionsoul.websnail.task.Task;
import org.lionsoul.websnail.util.UrlProcessor;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;

/**
 * @author yangjian
 **/
public class CustomTask implements Task
{
    private final Spider spider;
    private String url;

    public CustomTask(Spider spider, String url)
    {
        this.spider = spider;
        this.url = url;
    }


    @Override
    public Task setUrl(String url)
    {
        this.url = url;
        return this;
    }

    @Override
    public String getUrl()
    {
        return url;
    }

    @Override
    public void run()
    {
        String requestUrl = url;
        UrlProcessor urlProcessor = spider.getOptions().getUrlProcessor();
        if (null != urlProcessor) {
            requestUrl = urlProcessor.process(url);
        }
        if (requestUrl == null) {
            return;
        }

        WebDriverDownloader downloader = (WebDriverDownloader) spider.getOptions().getDownloader();
        SnailWebDriver driver = downloader.getWebDriverBuilder().build(downloader.getDriverProcessor());
        while (null == driver) {
            try {
                Thread.sleep(spider.getOptions().getWorkerBusySleepTime());
            } catch (InterruptedException e) {
                System.out.println("The WebDriver pool is full and all WebDriver is busing, rebuild later...");
            }
            driver = downloader.getWebDriverBuilder().build(downloader.getDriverProcessor());
        }

        try {
            driver.getWebDriver().get(requestUrl);
            // 注入 cookie
            downloader.getDriverProcessor().beforeProcess(driver);
            Thread.sleep(3000);
            WebElement webElement;
            try {
                webElement = driver.getWebDriver().findElement(By.id("J_goodsList"));
            } catch (NoSuchElementException e) {
                return;
            }

            String html = webElement.getAttribute("outerHTML");
            // 解析文档内容
            Document doc = Jsoup.parse(html);
            Elements items = doc.getElementsByClass("gl-item");
            for (Element item : items) {
                String price = item.selectXpath("div/div[@class=\"p-price\"]/strong/i").get(0).text();
                String title = item.getElementsByClass("p-name").get(0).selectXpath("a/em").text();
                String url = item.getElementsByClass("p-name").get(0).getElementsByIndexEquals(0).attr("href");
                // 是否自营
                String mark = "";
                Elements icons = item.selectXpath("div/div[@class=\"p-icons\"]/i");
                if (icons.size() > 0 && StringUtils.equals("自营", icons.get(0).text())) {
                    mark = "自营";
                }

                System.out.printf("商品名称：%s, 价格：%s, 链接地址：https:%s, %s%n", title, price, url, mark);

                // 添加到 todolist
                spider.pushRequestUrl("https:" + url);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            driver.setState(SnailWebDriver.IDLE);
        }

    }
}
